import { useState, useEffect, useContext, useRef } from "react";
import api from "@/services/api";
import { useNavigate, useSearchParams } from "react-router-dom";
import { cn } from "@/lib/utils";
import { useTheme } from "@/hooks/useTheme";
import { motion } from "framer-motion";
import { toast } from "sonner";
import { AuthContext } from "@/App";
import UserService from "@/services/user";


interface Project {
  projectId: string;
  projectName: string;
  projectIcon: string;
  teamId: string;
  desc: string;
  createUser: {
    userId: string;
    userName: string;
    userIcon: string;
    account: string;
  };
  createTime: string;
  type: string;
  permission: string;
}

const iconOptions = [
  "fa-solid fa-folder",
  "fa-solid fa-file-code",
  "fa-solid fa-server",
  "fa-solid fa-database",
  "fa-solid fa-cloud",
  "fa-solid fa-mobile-screen",
  "fa-solid fa-globe"
];

export default function ProjectList() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { isAuthenticated, userInfo, logout, currentTeam, saveProjectContext } = useContext(AuthContext);
  const { theme, toggleTheme, isDark } = useTheme();
  const [projects, setProjects] = useState<Project[]>([]);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [newProject, setNewProject] = useState({
    projectName: "",
    projectIcon: "fa-solid fa-folder",
    desc: ""
  });
  const [editingProject, setEditingProject] = useState<Project | null>(null);
  const [openDropdownId, setOpenDropdownId] = useState<string | null>(null);
  const dropdownRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});

  useEffect(() => {
    const fetchProjects = async () => {
      if (currentTeam) {
        try {
          const projects = await UserService.getProjectListByTeamId(currentTeam);
          setProjects(projects);
        } catch (e) {
          setProjects([]);
        }
      } else {
        setProjects([]);
      }
    };
    fetchProjects();
  }, [currentTeam]);

  useEffect(() => {
    // 检查URL参数是否需要直接显示创建模态框
    if (searchParams.get("create") === "true") {
      setShowCreateModal(true);
    }
  }, [searchParams]);

  const [isCreating, setIsCreating] = useState(false);

  const handleCreateProject = async () => {
    if (!newProject.projectName.trim()) {
      toast.error("项目名称不能为空");
      return;
    }
    setIsCreating(true);
    try {
      const res = await UserService.addProject({
        teamId: currentTeam || "1934856879721684993",
        projectName: newProject.projectName,
        projectIcon: newProject.projectIcon,
        projectDesc: newProject.desc
      });
      const result = res as any;
      if (result.code === 200 && result.success) {
        // 新建项目后刷新项目列表
        try {
          const projects = await UserService.getProjectListByTeamId(currentTeam || "");
          setProjects(projects);
          toast.success(`项目 ${newProject.projectName} 创建成功`);
        } catch (error) {
          toast.success(`项目 ${newProject.projectName} 创建成功，但刷新数据失败`);
        }
      }
    } catch (error: any) {
      let errorMessage = '创建项目失败';
      if (error.isNetworkError) {
        errorMessage = `网络连接问题: 无法连接到服务器(${api.defaults.baseURL})`;
      } else if (error.isCorsError) {
        errorMessage = `跨域问题: 请确保服务器已配置允许来自 ${window.location.origin} 的请求`;
      } else if (error.response) {
        errorMessage = error.response.data?.message || 
                      `服务器错误 (${error.response.status})`;
      }

      toast.error(
        <div className="space-y-1">
          <div className="font-medium">创建项目失败</div>
          <div className="text-sm">{errorMessage}</div>
          {error.isCorsError && (
            <div className="text-xs mt-2">
              跨域问题解决方案:
                <br/>1. 检查服务器CORS配置
                <br/>2. 确保允许来自 {window.location.origin} 的请求
                <br/>3. 确保支持OPTIONS预检请求
            </div>
          )}
        </div>,
        { duration: 10000 }
      );
    } finally {
      setIsCreating(false);
    }
  };

  const [isUpdatingProject, setIsUpdatingProject] = useState(false);

  const handleUpdateProject = async () => {
    if (!editingProject || !editingProject.projectName.trim()) {
      toast.error("项目名称不能为空");
      return;
    }
    setIsUpdatingProject(true);
    try {
      const res = await UserService.editProject({
        projectId: editingProject.projectId,
        projectName: editingProject.projectName,
        projectIcon: editingProject.projectIcon,
        projectDesc: editingProject.desc
      });
      const result = res as any;
      if (result.code === 200 && result.success) {
        // 编辑项目后刷新项目列表
        try {
          const projects = await UserService.getProjectListByTeamId(currentTeam || "");
          setProjects(projects);
          setEditingProject(null);
          toast.success("项目信息已更新");
        } catch (error) {
          toast.success("项目信息已更新，但刷新数据失败");
        }
      }
    } catch (error: any) {
      console.error('更新项目信息失败:', error);
      toast.error(error.message || '更新项目信息失败');
    } finally {
      setIsUpdatingProject(false);
    }
  };

  const handleDeleteProject = (id: string) => {
    const projectName = projects.find(p => p.projectId === id)?.projectName;
    setProjects(projects.filter(project => project.projectId !== id));
    toast.success(`项目 ${projectName} 已删除`);
  };

  // 监听点击外部关闭下拉
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (openDropdownId && dropdownRefs.current[openDropdownId]) {
        if (!dropdownRefs.current[openDropdownId]?.contains(event.target as Node)) {
          setOpenDropdownId(null);
        }
      }
    }
    if (openDropdownId) {
      document.addEventListener('mousedown', handleClickOutside);
    } else {
      document.removeEventListener('mousedown', handleClickOutside);
    }
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [openDropdownId]);

  return (
    <div className={cn(
      "min-h-screen flex flex-col bg-transparent",
      isDark ? "text-gray-100" : "text-gray-900"
    )}>
      {/* 导航栏 */}
      <header className={cn(
        "sticky top-0 z-10 p-2 border-b",
        isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
      )}>
        <div className="container mx-auto flex justify-between items-center">
          <div className="flex items-center space-x-4">
            <button 
              onClick={() => navigate(-1)}
              className={cn(
                "px-3 py-1 rounded-md font-mono flex items-center",
                isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
              )}
            >
              <i className="fa-solid fa-arrow-left mr-2"></i>
              返回
            </button>
            <h1 className="font-mono font-bold text-xl">项目管理</h1>
            {currentTeam && (
              <span className="text-sm font-mono px-3 py-1 rounded-full bg-gray-100 dark:bg-gray-700">
                团队ID: {currentTeam}
              </span>
            )}
          </div>
          
          <div className="flex items-center space-x-4">
             <button 
              onClick={() => {
                console.log('新建项目按钮被点击');
                setShowCreateModal(true);
              }}
              className={cn(
                "px-4 py-2 rounded-md font-medium",
                isDark 
                  ? "bg-blue-600 hover:bg-blue-700" 
                  : "bg-orange-500 hover:bg-orange-600",
                "text-white"
              )}
            >
              <i className="fa-solid fa-plus mr-2"></i>
              新建项目
             </button>
           </div>
        </div>
        {isAuthenticated && (
          <div className="relative group">
            <button className="flex items-center space-x-2">
              <div className="w-10 h-10 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
                <i className="fa-solid fa-user text-gray-600 dark:text-gray-300"></i>
              </div>
            </button>
            <div className="absolute right-0 mt-2 w-48 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 invisible group-hover:visible transition-all">
              <div className="py-1">
                <div className="px-4 py-2 text-sm text-gray-700 dark:text-gray-200">
                  {userInfo?.userName || '用户'}
                </div>
                <button 
                  onClick={logout}
                  className="block w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700"
                >
                  <i className="fa-solid fa-right-from-bracket mr-2"></i>
                  退登
                </button>
              </div>
            </div>
          </div>
        )}
      </header>

      {/* 项目列表 */}
      <main className="flex-1 container mx-auto p-4 md:p-8">
         {projects.length === 0 ? (
          <motion.div 
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="flex flex-col items-center justify-center h-full py-12"
          >
            <div className={cn(
              "p-6 rounded-xl shadow-lg text-center mb-6",
              isDark ? "bg-gray-800" : "bg-white"
            )}>
              <i className="fa-solid fa-folder-plus text-5xl mb-4 text-blue-500"></i>
              <h2 className="text-xl font-bold mb-2">
                {currentTeam ? '该团队下暂无项目' : '您还没有任何项目'}
              </h2>
              <p className="text-gray-500 mb-4">
                {currentTeam ? '为该团队创建第一个项目' : '立即创建您的第一个项目'}
              </p>
              <button 
                onClick={() => setShowCreateModal(true)}
                className={cn(
                  "px-6 py-3 rounded-md font-medium",
                  isDark 
                    ? "bg-blue-600 hover:bg-blue-700" 
                    : "bg-blue-500 hover:bg-blue-600",
                  "text-white"
                )}
              >
                <i className="fa-solid fa-plus mr-2"></i>
                新建项目
              </button>
            </div>
          </motion.div>
         ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
               {projects.map(project => (
                 <motion.div
                   key={project.projectId}
                   whileHover={{ y: -5 }}
                   className={cn(
                     "p-4 rounded-xl shadow-md cursor-pointer border relative overflow-hidden",
                     isDark ? "bg-gray-800" : "bg-white"
                   )}
                   onClick={() => {
                     if (project.projectId && project.teamId) {
                       saveProjectContext(
                         project.projectId,
                         project.teamId,
                         (project as any).type,
                         (project as any).permission
                       );
                       localStorage.setItem('currentProjectType', (project as any).type || '');
                       localStorage.setItem('currentProjectPermission', (project as any).permission || '');
                     }
                     navigate('/project-detail');
                   }}
                 >
                  {/* 三点更多按钮，仅拥有者可见 */}
                  {project.type === 'OWNER' && (
                    <div
                      className="absolute top-2 right-2 z-30"
                      ref={el => dropdownRefs.current[project.projectId] = el}
                      onClick={e => e.stopPropagation()}
                    >
                      <button
                        onClick={e => {
                          e.stopPropagation();
                          setOpenDropdownId(openDropdownId === project.projectId ? null : project.projectId);
                        }}
                        className={cn(
                          "p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 focus:outline-none"
                        )}
                        tabIndex={-1}
                      >
                        <i className="fa-solid fa-ellipsis-vertical"></i>
                      </button>
                      {openDropdownId === project.projectId && (
                        <div
                          className="absolute right-0 mt-2 w-32 bg-white dark:bg-gray-800 shadow-lg rounded-md border border-gray-100 dark:border-gray-700 z-50"
                          onClick={e => e.stopPropagation()}
                        >
                          <button
                            onClick={e => {
                              e.stopPropagation();
                              setEditingProject(project);
                              setOpenDropdownId(null);
                            }}
                            className="block w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700"
                            tabIndex={-1}
                          >
                            <i className="fa-solid fa-pen mr-2"></i>编辑
                          </button>
                          <button
                            onClick={e => {
                              e.stopPropagation();
                              handleDeleteProject(project.projectId);
                              setOpenDropdownId(null);
                            }}
                            className="block w-full text-left px-4 py-2 text-sm hover:bg-red-100 dark:hover:bg-red-700 text-red-600 dark:text-red-400"
                            tabIndex={-1}
                          >
                            <i className="fa-solid fa-trash mr-2"></i>删除
                          </button>
                        </div>
                      )}
                    </div>
                  )}
                  <div className="flex items-center space-x-3 mb-3">
                    <i className={cn(
                      project.projectIcon,
                      "text-2xl",
                      isDark ? "text-blue-400" : "text-blue-500"
                    )}></i>
                    <div>
                      <h3 className="font-mono font-bold">{project.projectName}</h3>
                    </div>
                  </div>
                  <div className="text-sm mb-3">
                    <p className="text-gray-500 line-clamp-2">{project.desc || '暂无描述'}</p>
                  </div>
                </motion.div>
            ))}
          </div>
        )}
      </main>

      {/* 新建项目模态框 */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className={cn(
              "w-full max-w-md p-6 rounded-xl shadow-lg",
              isDark ? "bg-gray-800" : "bg-white"
            )}
          >
            <div className="flex justify-between items-center mb-4">
              <h2 className="font-mono font-bold text-xl">新建项目</h2>
              <button
                onClick={() => setShowCreateModal(false)}
                className={cn(
                  "p-1 rounded-full",
                  isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
                )}
              >
                <i className="fa-solid fa-times"></i>
              </button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block font-mono text-sm mb-1">项目名称</label>
                <input
                  type="text"
                  value={newProject.projectName}
                  onChange={(e) => setNewProject({...newProject, projectName: e.target.value})}
                  className={cn(
                    "w-full px-4 py-2 rounded-md border font-mono",
                    "focus:outline-none focus:ring-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                      : "border-gray-300 focus:ring-orange-500 bg-white"
                  )}
                  placeholder="输入项目名称"
                />
              </div>
              <div>
                <label className="block font-mono text-sm mb-1">项目图标</label>
                <div className="grid grid-cols-4 gap-2 mb-2">
                  {iconOptions.map(icon => (
                    <button
                      key={icon}
                      onClick={() => setNewProject({...newProject, projectIcon: icon})}
                      className={cn(
                        "p-2 rounded-md flex items-center justify-center",
                        newProject.projectIcon === icon 
                          ? (isDark ? "bg-blue-600" : "bg-orange-500") 
                          : (isDark ? "hover:bg-gray-700" : "hover:bg-gray-100")
                      )}
                    >
                      <i className={cn(
                        icon,
                        "text-xl",
                        newProject.projectIcon === icon ? "text-white" : 
                          (isDark ? "text-blue-400" : "text-orange-500")
                      )}></i>
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="block font-mono text-sm mb-1">项目描述</label>
                <textarea
                  value={newProject.desc}
                  onChange={(e) => setNewProject({...newProject, desc: e.target.value})}
                  className={cn(
                    "w-full px-4 py-2 rounded-md border font-mono",
                    "focus:outline-none focus:ring-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                      : "border-gray-300 focus:ring-orange-500 bg-white"
                  )}
                  placeholder="输入项目描述"
                  rows={3}
                />
              </div>
              <div className="flex justify-end space-x-2">
                <button
                  onClick={() => setShowCreateModal(false)}
                  className={cn(
                    "px-4 py-2 rounded-md font-medium",
                    isDark 
                      ? "bg-gray-700 hover:bg-gray-600" 
                      : "bg-gray-200 hover:bg-gray-300"
                  )}
                >
                  取消
                </button>
                 <button
                  onClick={handleCreateProject}
                  disabled={isCreating}
                  className={cn(
                    "px-4 py-2 rounded-md font-medium flex items-center justify-center",
                    isDark 
                      ? "bg-blue-600 hover:bg-blue-700" 
                      : "bg-orange-500 hover:bg-orange-600",
                    "text-white",
                    isCreating ? "opacity-75" : ""
                  )}
                >
                  {isCreating ? (
                    <>
                      <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                      创建中...
                    </>
                  ) : "创建"}
                </button>
              </div>
            </div>
          </motion.div>
        </div>
      )}

      {/* 编辑项目模态框 */}
      {editingProject && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className={cn(
              "w-full max-w-md p-6 rounded-xl shadow-lg",
              isDark ? "bg-gray-800" : "bg-white"
            )}
          >
            <div className="flex justify-between items-center mb-4">
              <h2 className="font-mono font-bold text-xl">编辑项目</h2>
              <button
                onClick={() => setEditingProject(null)}
                className={cn(
                  "p-1 rounded-full",
                  isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
                )}
              >
                <i className="fa-solid fa-times"></i>
              </button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block font-mono text-sm mb-1">创建者</label>
                <div className={cn(
                  "p-3 rounded-md flex items-center space-x-3",
                  isDark ? "bg-gray-700" : "bg-gray-100"
                )}>
                  <i className={cn(
                    editingProject.createUser.userIcon,
                    "text-xl",
                    isDark ? "text-blue-400" : "text-orange-500"
                  )}></i>
                  <div>
                    <p className="font-mono">{editingProject.createUser.userName}</p>
                    <p className="text-sm text-gray-500">{editingProject.createUser.account}</p>
                  </div>
                </div>
              </div>
              <div>
                <label className="block font-mono text-sm mb-1">项目名称</label>
                <input
                  type="text"
                  value={editingProject.projectName}
                  onChange={(e) => setEditingProject({...editingProject, projectName: e.target.value})}
                  className={cn(
                    "w-full px-4 py-2 rounded-md border font-mono",
                    "focus:outline-none focus:ring-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                      : "border-gray-300 focus:ring-orange-500 bg-white"
                  )}
                  placeholder="输入项目名称"
                />
              </div>
              <div>
                <label className="block font-mono text-sm mb-1">团队ID</label>
                <input
                  type="text"
                  value={editingProject.teamId}
                  onChange={(e) => setEditingProject({...editingProject, teamId: e.target.value})}
                  className={cn(
                    "w-full px-4 py-2 rounded-md border font-mono",
                    "focus:outline-none focus:ring-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                      : "border-gray-300 focus:ring-orange-500 bg-white"
                  )}
                  placeholder="输入团队ID"
                />
              </div>
              <div>
                <label className="block font-mono text-sm mb-1">项目图标</label>
                <div className="grid grid-cols-4 gap-2 mb-2">
                  {iconOptions.map(icon => (
                    <button
                      key={icon}
                      onClick={() => setEditingProject({...editingProject, projectIcon: icon})}
                      className={cn(
                        "p-2 rounded-md flex items-center justify-center",
                        editingProject.projectIcon === icon 
                          ? (isDark ? "bg-blue-600" : "bg-orange-500") 
                          : (isDark ? "hover:bg-gray-700" : "hover:bg-gray-100")
                      )}
                    >
                      <i className={cn(
                        icon,
                        "text-xl",
                        editingProject.projectIcon === icon ? "text-white" : 
                          (isDark ? "text-blue-400" : "text-orange-500")
                      )}></i>
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="block font-mono text-sm mb-1">项目描述</label>
                <textarea
                  value={editingProject.desc}
                  onChange={(e) => setEditingProject({...editingProject, desc: e.target.value})}
                  className={cn(
                    "w-full px-4 py-2 rounded-md border font-mono",
                    "focus:outline-none focus:ring-2",
                    isDark 
                      ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                      : "border-gray-300 focus:ring-orange-500 bg-white"
                  )}
                  placeholder="输入项目描述"
                  rows={3}
                />
              </div>
              <div className="flex justify-end space-x-2">
                <button
                  onClick={() => setEditingProject(null)}
                  className={cn(
                    "px-4 py-2 rounded-md font-medium",
                    isDark 
                      ? "bg-gray-700 hover:bg-gray-600" 
                      : "bg-gray-200 hover:bg-gray-300"
                  )}
                >
                  取消
                </button>
                <button
                  onClick={handleUpdateProject}
                  className={cn(
                    "px-4 py-2 rounded-md font-medium",
                    isDark 
                      ? "bg-blue-600 hover:bg-blue-700" 
                      : "bg-orange-500 hover:bg-orange-600",
                    "text-white"
                  )}
                >
                   {isUpdatingProject ? (
                     <>
                       <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                       保存中...
                     </>
                   ) : '保存'}
                 </button>
              </div>
            </div>
          </motion.div>
        </div>
      )}
    </div>
  );
}